package org.example.cake.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 阿里云 OSS 工具类
 */
@Component
public class AliOSSUtils {

    private String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    private String accessKeyId = "LTAI5tLnosDcrroWdGVJ7E5s";
    private String accessKeySecret = "itvNwpjZqdRf3ccWsiQJFqKe5YZUdY";
    private String bucketName = "cakeapp";

    public String upload(MultipartFile file) throws IOException {
        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 获取原始文件名并处理特殊字符
            String originalFilename = file.getOriginalFilename();
            System.out.println("originalFilename = " + originalFilename);
            // 移除可能存在的路径信息（只保留文件名）
            String safeFilename = new File(originalFilename).getName();

            // 替换特殊字符为下划线（可选）
            safeFilename = safeFilename.replaceAll("[^a-zA-Z0-9.-]", "_");

            // 获取文件扩展名
            String fileExtension = "";
            int lastDotIndex = safeFilename.lastIndexOf('.');
            if (lastDotIndex > 0) {
                fileExtension = safeFilename.substring(lastDotIndex);
                safeFilename = safeFilename.substring(0, lastDotIndex);
            }

            // 组合最终文件名（可添加时间戳避免重复）
            String fileName = safeFilename + "_" + System.currentTimeMillis() + fileExtension;

            // 上传文件
            ossClient.putObject(bucketName, fileName, file.getInputStream());

            // 构建完整的图片访问URL
            String fileUrl = "https://" + bucketName + "." + endpoint.substring(endpoint.indexOf("//") + 2) + "/" + fileName;
            System.out.println("fileUrl = " + fileUrl);
            // 返回完整的图片URL
            return fileUrl;
        } finally {
            // 关闭OSSClient
            ossClient.shutdown();
        }
    }
}
